package com.ruoyi.framework.websocket;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Semaphore;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.ruoyi.system.domain.ReportInfo;
import com.ruoyi.system.service.IReportInfoService;
import org.apache.ibatis.javassist.tools.web.Webserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/message")
public class WebSocketServer {


    @Autowired
    IReportInfoService reportInfoService;
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) throws Exception {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag) {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        } else {
            // 添加用户
            WebSocketUsers.put(session.getId(), session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
            WebSocketUsers.sendMessageToUserByText(session, "true");
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session) {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
        WebSocketUsers.remove(session.getId());
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info("\n 连接异常 - {}", sessionId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println(message);
        try {
            // 消息
            WebUserInfo webUserInfo = JSONObject.parseObject(message, WebUserInfo.class);
            // 欢迎语
            if (webUserInfo.getLoginId() != null) {
                WebSocketUsers.put(webUserInfo.getLoginId(), session);
                System.out.println(WebSocketUsers.getUsers().get(webUserInfo.getLoginId()));
            }
            // 网页端给我的消息
            if (Objects.equals(webUserInfo.getLoginId(), "-1")) {
                String sendUserId = webUserInfo.getId();
                if(sendUserId != null && !Objects.equals(sendUserId,"")){
                    Session value = WebSocketUsers.getUsers().get(sendUserId);
                    WebSocketUsers.sendMessageToUserByText(value, webUserInfo.getAddress());
                }else {
                    WebSocketUsers.sendMessageToUsersByText("false");
                }
            } else {
                // 其他app用户的消息
                Session value1 = WebSocketUsers.getUsers().get("-1");
                if(webUserInfo.getAddress() != null) {
                    WebSocketUsers.sendMessageToUserByText(value1, message);
                }
            }

            Map<String, Session> values = WebSocketUsers.getUsers();
            String address = "";
            reportInfoService = SpringContextUtils.getBean(IReportInfoService.class);
            List<ReportInfo> reportInfoList = Lists.newArrayList();
            for (String in : values.keySet()) {
                System.out.println("在线用户：");
                Session str = values.get(in);
                System.out.println(str);
                ReportInfo reportInfo = new ReportInfo();
                reportInfo.setLoginId(in);
                List<ReportInfo> reportInfoList1 = reportInfoService.selectReportInfoList(reportInfo);
                if(!reportInfoList1.isEmpty()){
                    reportInfoList.add(reportInfoList1.get(0));
                }
            }


            WebUserInfo webUserInfo1 = new WebUserInfo();
            webUserInfo1.setId("list");
            webUserInfo1.setAddress(JSON.toJSONString(reportInfoList, SerializerFeature.DisableCircularReferenceDetect));
            Session value1 = WebSocketUsers.getUsers().get("-1");
            WebSocketUsers.sendMessageToUserByText(value1, JSON.toJSONString(webUserInfo1));

        } catch (Exception e) {
            e.printStackTrace();
            WebSocketUsers.sendMessageToUserByText(session, "false");
            WebSocketUsers.remove(session.getId());
        }

    }
}
